using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;

using PickGold.Util;

namespace PickGold.Web
{
	public class CDataExportToExcel : CDataToExcel
	{
		private HttpRequest _Request;
		private HttpResponse _Response;
		private HttpServerUtility _Server;

		public CDataExportToExcel()
			: base()
		{
			this._Server = HttpContext.Current.Server;
			this._Request = HttpContext.Current.Request;
			this._Response = HttpContext.Current.Response;
		}

		private CDataExportToExcel(IPage page)
			: base()
		{
			this._Server = page.Server;
			this._Request = page.Request;
			this._Response = page.Response;
		}
		private CDataExportToExcel(Page page)
			: base()
		{
			this._Server = page.Server;
			this._Request = page.Request;
			this._Response = page.Response;
		}
		public CDataExportToExcel(Stream outStream)
			: base(outStream)
		{
			this._Server = null;
			this._Request = null;
			this._Response = null;
		}

		protected override string GetCompany()
		{
			if (this._Request == null)
				return base.GetCompany();

			return this._Request.Url.Host;
		}

		protected override bool CanContinue()
		{
			if (this._Response != null)
				return this._Response.IsClientConnected && this._OutStream.CanWrite;

			return base.CanContinue();
		}

		protected string ExportToPage()
		{
			if (this._Response == null)
				return this.ExportToStream();

			if (this._Server != null && this._Server.ScriptTimeout < int.MaxValue)
				this._Server.ScriptTimeout = int.MaxValue;
			this._Response.Clear();
			this._Response.Expires = -1;
			this._Response.Buffer = false;
			this._Response.Charset = "GB2312";
			this._Response.ContentType = "application/ms-excel";
			this._Response.ContentEncoding = Encoding.UTF7;
			if (string.IsNullOrEmpty(this._FileName))
				this._FileName = HttpContext.Current.Timestamp.Ticks.ToString();
			this._Response.AppendHeader(HttpHeaderKey.CONTENT_DISPOSITION, "attachment;filename=" + HttpUtility.UrlEncode(this._FileName, Encoding.UTF8) + ".xls");
			this._OutStream = this._Response.OutputStream;
			string t = this.ExportToStream();
			this._Response.End();
			return t;
		}

		protected override string ExportToStream()
		{
			if (this._OutStream == null && this._Response != null)
				return this.ExportToPage();

			return base.ExportToStream();
		}
		//
	}
	//
}
//
